//
//  PrefectPersonalInfoViewController.m
//  PigMarket
//
//  Created by mac on 2019/3/13.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "PrefectPersonalInfoViewController.h"
#import "ModifyUserInfoViewController.h"
#import "ModifyPhotoViewController.h"
#import "SelectTagsViewController.h"
#import "AdoptPigViewController.h"
#import "SelectInviterViewController.h"

#import "UserInfoCell.h"
#import "MeatMePhotosCell.h"

#import "STPickerDate.h"
#import "STPickerArea.h"
#import "STPickerSingle.h"

#import <TZImagePickerController.h>

#define kBind @"去绑定"
#define kUnbind @"解绑"

@interface PrefectPersonalInfoViewController ()<UITableViewDelegate,UITableViewDataSource,STPickerAreaDelegate, STPickerDateDelegate,TZImagePickerControllerDelegate>

/**
 tableView
 */
@property (nonatomic , strong) UITableView *tableview;

/**
 leftTitleArr
 */
@property (nonatomic , strong) NSArray *dataArr;


/**
 提交btn
 */
@property (nonatomic , strong) UIButton *commitBtn;


/**
 area
 */
@property (nonatomic , strong) NSString *area;


/**
 sex
 */
@property (nonatomic , strong) NSNumber *sex;


/**
 birthDate
 */
@property (nonatomic , strong) NSString *birthDate;


/**
 password
 */
@property (nonatomic , strong) NSString *password;


/**
 param
 */
@property (nonatomic , strong) PersonalInformationParam *param;


/**
 照片NameArr 入参
 */
@property (nonatomic , strong) NSMutableArray *photoNameArr;


/**
 选择的头像图片
 */
@property (nonatomic , strong) UIImage *selectHeaderImg;


/**
 拍照和相册选择照片
 */
@property (nonatomic , strong) ImagePicker *imagePicker;


/**
 标签id数组
 */
@property (nonatomic , strong) NSMutableArray<NSNumber *> *selectTagsIdArr;


/**
 标签名字数组
 */
@property (nonatomic , strong) NSMutableArray<NSString *> *selectTagsNameArr;


/**
 保存上传完图片的Array
 */
@property (nonatomic, strong) NSMutableArray<Photos *> *photos;


//是否更新相片
@property (nonatomic, assign) BOOL isUpdatePhoto;

/**
 wechatUid
 */
@property (nonatomic , strong) NSString *wechatUid;
/**
 sinaUid
 */
@property (nonatomic , strong) NSString *sinaUid;
/**
 qqUid
 */
@property (nonatomic , strong) NSString *qqUid;
/**
 bindOrUnbind
 */
@property (nonatomic , strong) NSString *bindOrUnbind;
/**
 uid
 */
@property (nonatomic , strong) NSString *uid;
/**
 withdrawOpenId
 */
@property (nonatomic , strong) NSString *withdrawOpenId;
/**
 UMSocialPlatformType
 */
@property (nonatomic , assign) UMSocialPlatformType umSocialPlatformType;


@property (nonatomic, assign) NSInteger aimsSection;


@property (nonatomic, strong) FMTagsView *tagsView;


@property (nonatomic, strong) NSArray *tagArray;


@property (nonatomic, strong) NSArray *aimTags;


@end

@implementation PrefectPersonalInfoViewController

#pragma mark - view life cycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.baseNavView.navTitleLabel.text = self.title;
    self.isUpdatePhoto = NO;
    
    [self setUpView];
    self.tableview.backgroundColor = mBackgroudColor;
}


#pragma mark - init method

- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    [self.view addSubview:self.tableview];
}


- (void) initLayout {
//    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(TJ_NavBarHeight);
//        make.left.right.bottom.mas_equalTo(self.view);
//    }];
    
    self.tableview.mj_y = TJ_NavBarHeight;
    self.tableview.width = KScreenWidth;
    self.tableview.height = KScreenHeight - TJ_NavBarHeight;
    self.tableview.mj_x = 0;
}


- (void) initAction {
    
    [self.commitBtn addTarget:self action:@selector(commitTapped) forControlEvents:UIControlEventTouchUpInside];
    
    //修改昵称通知
    [kNotificationCenter addObserver:self selector:@selector(refreshData) name:NotificationNickNameChanged object:nil];
    //修改个性签名
    [kNotificationCenter addObserver:self selector:@selector(refreshData) name:NotificationRemarkChanged object:nil];
    //设置密码
    [kNotificationCenter addObserver:self selector:@selector(refreshData) name:NotificationPasswordChanged object:nil];
    //添加照片
    [kNotificationCenter addObserver:self selector:@selector(getPhotosName:) name:NotificationPhotosNameChanged object:nil];
    //删除照片
    [kNotificationCenter addObserver:self selector:@selector(refreshData1) name:NotificationPhotoDeleteChange object:nil];

}


- (void)initData {
    
    if (self.userInfoModel.tagsIds) {
        self.tagArray= [self.userInfoModel.tagsIds componentsSeparatedByString:@"-"];
    }
    
    [self obtainTagsData];
    
    if (!self.userInfoModel) {
        self.userInfoModel = [[UserDetailInfo alloc] init];
    }
    
    [self requestAllPhotos];

    NSString *headerImg = self.userInfoModel.headImg ? self.userInfoModel.headImg : @"";
    NSString *nickName = self.userInfoModel.nickName ? self.userInfoModel.nickName : @"";
    NSString *sex = @"";
    if ([self.userInfoModel.sex intValue] == 1) {
        sex = @"男";
    }else if([self.userInfoModel.sex intValue] == 2){
        sex = @"女";
    }
    NSString *birthDay = self.userInfoModel.birthDate ? self.userInfoModel.birthDate : @"";
    NSString *area = self.userInfoModel.regionName ? self.userInfoModel.regionName : @"";
    NSString *remark = self.userInfoModel.personality ? self.userInfoModel.personality : @"";
    NSString *inviter = self.userInfoModel.inviteCode ? self.userInfoModel.inviteCode : @"";
    
    NSString *orginPassword = self.userInfoModel.password ?self.userInfoModel.password : @"";
    NSString *password = @"";
    
    if (orginPassword.length >0) {
        password = [NSString replaceStringWithAsterisk:orginPassword startLocation:0 lenght:orginPassword.length];
    }
    
    self.wechatUid = [UserInfoDataProvider sharedInstance].userInfo.wxOpenid;
    self.sinaUid = [UserInfoDataProvider sharedInstance].userInfo.wbOpenid;
    self.qqUid = [UserInfoDataProvider sharedInstance].userInfo.qqOpenid;
    
    
    if ([self.title isEqualToString:PrefectPersonalInfoTitle]) {
        self.aimsSection = 3;
        self.dataArr = @[@[@{@"icon":@"",@"title":@"头像",@"detail":headerImg},
                           @{@"icon":@"",@"title":@"昵称",@"detail":nickName},
                           @{@"icon":@"",@"title":@"性别*",@"detail":sex},
                           @{@"icon":@"",@"title":@"出生年月*",@"detail":birthDay},
                           @{@"icon":@"",@"title":@"所属城市*",@"detail":area}],
                         
                         @[@{@"icon":@"",@"title":@"设置密码*",@"detail":password}],
                         
                         @[@{@"icon":@"",@"title":@"个性签名",@"detail":remark}],
                         
                         @[@{@"icon":@"",@"title":@"常用照片",@"detail":@"去添加"}],
                         
                         @[@{@"title":@"微信",@"detail":[JTool iSNull:self.wechatUid] ? kBind : kUnbind},
                           @{@"title":@"QQ",@"detail":[JTool iSNull:self.qqUid] ? kBind : kUnbind},
                           @{@"title":@"微博",@"detail":[JTool iSNull:self.sinaUid] ? kBind : kUnbind}]];
        
    }else if ([self.title isEqualToString:ModifyPersonalInfoTitle]){
        self.aimsSection = 2;
        self.dataArr = @[@[@{@"icon":@"",@"title":@"头像",@"detail":headerImg},
                           @{@"icon":@"",@"title":@"昵称",@"detail":nickName},
                           @{@"icon":@"",@"title":@"性别*",@"detail":sex},
                           @{@"icon":@"",@"title":@"出生年月*",@"detail":birthDay},
                           @{@"icon":@"",@"title":@"所属城市*",@"detail":area}],
                         @[@{@"icon":@"",@"title":@"个性签名",@"detail":remark}],
                         @[@{@"icon":@"",@"title":@"常用照片",@"detail":@"去添加"}],
                         @[@{@"icon":@"",@"title":@"我的邀请人",@"detail":inviter}],
                         @[@{@"icon":@"",@"title":@"我的标签",@"detail":@"修改"}]];
    }
}



#pragma mark - target action

- (void)commitTapped {
    [self commitDataRequest];
}


//获取已上传的图片nameArr 入参使用
- (void)getPhotosName:(NSNotification *)notification {
    
    NSMutableArray *nameArr = notification.userInfo[@"photoNameModel"];
    
    for (Photos *model in nameArr) {
        [self.photos addObject:model];
        [self.tableview reloadData];
    };
}


#pragma mark - private method

//获取图片列表请求
- (void)requestAllPhotos {
    [self.photos removeAllObjects];
    NSNumber *memberID = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getPhotosWithMemberId:memberID] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        
        [self.photos addObjectsFromArray:photoList.imgList];
        [self.tableview reloadData];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}

//获取Tags标签数据
- (void)obtainTagsData{
    
    __block NSMutableArray *array = [NSMutableArray array];
    @weakify(self);
    
    [[[PigMarketApi sharedInstance] getUserTags] subscribeNext:^(UserTagsList * _Nullable tagsList) {
        @strongify(self);
        
        [self.tagArray enumerateObjectsUsingBlock:^(id  _Nonnull tagIndex, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [tagsList.groupType enumerateObjectsUsingBlock:^(UserTags * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [obj.tagsList enumerateObjectsUsingBlock:^(UserTag * _Nonnull aimTagIndex, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if ([tagIndex integerValue] == [aimTagIndex.tagsId integerValue]) {
                        [array addObject:aimTagIndex.tagsName];
                    }
                }];
                
            }];
        }];
        
        self.aimTags = [array copy];
        self.tagsView.tagsArray = self.aimTags;
        self.tagsView.height = [self getFMTagViewHeight:self.tagsView];
        
        [self.tableview reloadData];
        
    } error:^(NSError * _Nullable error) {
        
    }];
}


- (void)refreshData1{
    
    NSMutableArray *aims = [NSMutableArray array];
    NSNumber *memberID = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getPhotosWithMemberId:memberID] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        [aims addObjectsFromArray:photoList.imgList];
        
        self.photos = aims;
        
        kWeakSelf(self);
        [UIView performWithoutAnimation:^{
            NSIndexSet *reloadSet = [NSIndexSet indexSetWithIndex:weakself.aimsSection];
            [weakself.tableview reloadSections:reloadSet withRowAnimation:UITableViewRowAnimationNone];
        }];

    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}



//提交数据请求
- (void)commitDataRequest {
    
    NSString *phone = [UserInfoDataProvider sharedInstance].userInfo.phone;
    
    if ([JTool iSNull:self.userInfoModel.sex]) {
        [self toastWithContent:@"请选择性别"];
        return;
    }
    if ([JTool iSNull:self.userInfoModel.birthDate]) {
        [self toastWithContent:@"请选择出生年月"];
        return;
    }
    if ([JTool iSNull:self.userInfoModel.regionName]) {
        [self toastWithContent:@"请选择所属城市"];
        return;
    }

    PersonalInformationParam *param = [[PersonalInformationParam alloc] init];
    param.account = phone;
    
    if (self.userInfoModel.headImg) {
        NSArray *aimsArray = [self.userInfoModel.headImg componentsSeparatedByString:@"/"];
        param.headImg = [aimsArray lastObject];
    }
    
    param.nickName = self.userInfoModel.nickName;
    param.sex = self.userInfoModel.sex;
    param.birthDate = self.userInfoModel.birthDate;
    param.regionName = self.userInfoModel.regionName;
    param.personality = self.userInfoModel.personality;
    param.tagsIds = self.selectTagsIdArr;
    
    NSString *memberId = [NSString stringWithFormat:@"%@",[UserInfoDataProvider sharedInstance].userInfo.memberId];
    param.memberId = memberId;

    if (self.photos.count >0) { //照片添加
        
        for (Photos *model in self.photos) {
            
            if (model.imgName) {
                [self.photoNameArr addObject:model.imgName];
            }else{
                [self.photoNameArr addObject:model.name];
            }
        };
        param.imgs = self.photoNameArr;
    }
    
    
    if ([self.title isEqualToString:ModifyPersonalInfoTitle]) {//修改资料页面
        
        @weakify(self);
        [[[PigMarketApi sharedInstance] modifyUserInfoWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
            @strongify(self);
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            @strongify(self);
            [self handlingError:error];
        }];
    }else if([self.title isEqualToString:PrefectPersonalInfoTitle]){//完善个人资料页面
        if ([JTool iSNull:self.userInfoModel.password]) {
            [self toastWithContent:@"请设置密码"];
            return;
        }
        param.loginPwd = self.userInfoModel.password;
        

        @weakify(self);
        [self showProgressView];
        [[[PigMarketApi sharedInstance] userPersonalInformationWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
            @strongify(self);
            [self hideProgressView];
            [self.navigationController popToRootViewControllerAnimated:YES];
            //成功为登录成功状态  保存登录状态
            UserInfo *tempUserInfo = [UserInfoDataProvider sharedInstance].userInfo;
            tempUserInfo.isLogin = YES;
            [UserInfoDataProvider sharedInstance].userInfo = tempUserInfo;
            
            //通知我的界面未登录状态-->登录状态
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationLoginStatusChanged object:self userInfo:@{@"loginstatus" : @(YES)}];
            
        } error:^(NSError * _Nullable error) {
            @strongify(self);
            [self hideProgressView];
            [self handlingError:error];
        }];
    }
}


- (void)changeBindPlatform{
    
    if ([self.bindOrUnbind isEqualToString:kBind]) {//绑定
        @weakify(self);
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:self.umSocialPlatformType currentViewController:nil completion:^(id result, NSError *error) {
            @strongify(self);
            UMSocialUserInfoResponse *resp = result;
            //绑定是 保存openid 提现z操作时用到
            self.withdrawOpenId = resp.openid;
            
            //授权登录用uid
            self.uid = resp.uid;
            PMLog(@"%@",self.uid);
            
            //绑定借口请求
            [self changeBindRequest];
            
        }];
    } else if ([self.bindOrUnbind isEqualToString:kUnbind]) {//解绑
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [[UMSocialManager defaultManager] cancelAuthWithPlatform:self.umSocialPlatformType completion:^(id result, NSError *error) {
                
                self.uid = nil;
                //解绑借口请求
                [self changeBindRequest];
            }];
        });
    }
}


//绑定 解绑借口请求
- (void)changeBindRequest{
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    AccountBindParam *param = [[AccountBindParam alloc] init];
    param.memberId = memberId;
    param.account = self.uid;
    param.openId = self.withdrawOpenId;
    switch (self.umSocialPlatformType) {
        case UMSocialPlatformType_QQ:
            param.type = @2;
            break;
        case UMSocialPlatformType_WechatSession:
            param.type = @1;
            break;
        case UMSocialPlatformType_Sina:
            param.type = @4;
            break;
        default:
            param.type = @5;
            break;
    }
    
    if ([self.bindOrUnbind isEqualToString:kBind]) {//绑定
        param.isBind = @1;
    } else if ([self.bindOrUnbind isEqualToString:kUnbind]) {//解绑
        param.isBind = @0;
    }
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] accountBindOrUnbindWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self toastWithContent:[NSString stringWithFormat:@"%@成功",self.bindOrUnbind]];
        
        
        //更新缓存数据
        UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
        
        switch (self.umSocialPlatformType) {
            case UMSocialPlatformType_QQ:
                self.qqUid = self.uid;
                break;
            case UMSocialPlatformType_WechatSession:
                self.wechatUid = self.uid;
                
                break;
            case UMSocialPlatformType_Sina:
                self.sinaUid = self.uid;
                break;
            default:
                break;
        }
        userInfo.qqOpenid = self.qqUid;
        userInfo.wbOpenid = self.sinaUid;
        userInfo.wxOpenid = self.wechatUid;
        userInfo.withdrawWx = self.withdrawOpenId;
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        PMLog(@"%@",userInfo.wxOpenid);
        [self refreshData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//选择的标签
- (void)tagsWithTagsDic:(NSMutableDictionary *)dic {
    [self.selectTagsIdArr removeAllObjects];
    [self.selectTagsNameArr removeAllObjects];
    @weakify(self);
    [dic enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
        @strongify(self);
        [self.selectTagsIdArr addObject:key];
        [self.selectTagsNameArr addObject:obj];
    }];
}


- (void)showDatePicker {
    STPickerDate *pickerDate = [[STPickerDate alloc]init];
    [pickerDate setYearLeast:[NSDate obtainCurrentYear] - 70];
    [pickerDate setYearSum:71];
    [pickerDate setDelegate:self];
    [pickerDate setHeightPickerComponent:40];
    pickerDate.borderButtonColor = [UIColor primaryColor];
    [pickerDate.buttonRight setTitleColor:[UIColor primaryColor] forState:UIControlStateNormal];
    [pickerDate.buttonLeft setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
    pickerDate.buttonLeft.layer.borderColor = [UIColor clearColor].CGColor;
    pickerDate.buttonRight.layer.borderColor = [UIColor clearColor].CGColor;
    [pickerDate show];
    
}


- (void)showAreaPicker {
    STPickerArea *pickerArea = [[STPickerArea alloc] init];
    [pickerArea setDelegate:self];
    [pickerArea setSaveHistory:YES];
    [pickerArea setHeightPickerComponent:40];
    [pickerArea setTitle:@""];
    pickerArea.borderButtonColor = [UIColor primaryColor];
    [pickerArea setContentMode:STPickerContentModeBottom];
    [pickerArea.buttonRight setTitleColor:[UIColor primaryColor] forState:UIControlStateNormal];
    [pickerArea.buttonLeft setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
    pickerArea.buttonLeft.layer.borderColor = [UIColor clearColor].CGColor;
    pickerArea.buttonRight.layer.borderColor = [UIColor clearColor].CGColor;
    [pickerArea show];
}


- (void)showAlertActionWithItemsArr:(NSArray *)itemsArr {
    @weakify(self);
    [[AlertAction sharedInstance] showAlertSheetWithTitle:nil message:nil itemsArr:itemsArr selectItemBlock:^(NSString *selectItem) {
        @strongify(self);
        if ([selectItem isEqualToString:@"男"]) {
            self.sex = @(1);
            self.userInfoModel.sex = @(1);
            [self refreshData];
        }else if ([selectItem isEqualToString:@"女"]){
            self.sex = @(2);
            self.userInfoModel.sex = @(2);
            [self refreshData];
        }
        if ([selectItem isEqualToString:@"相册"]) {
            [self openAlbum];
        } else if ([selectItem isEqualToString:@"拍照"]){
            [self takePhoto];
        }
        
    }];
}


//拍照
- (void)takePhoto {
    @weakify(self);
    self.imagePicker.cameraAllowsEditing = YES;
    [self.imagePicker takeCameraCallBack:^(UIImage *photos) {
        @strongify(self);
        self.selectHeaderImg = photos;
        [self.tableview reloadData];
        //上传图片
        [self uploadPhotoRequestWithPhotosArr:@[self.selectHeaderImg]];
    }];
}


//相册
- (void)openAlbum {
    
    self.imagePicker.maxImages = 1;
    self.imagePicker.allowTakeVideo = NO;
    self.imagePicker.allowCrop = YES;
    self.imagePicker.needCircleCrop = YES;
    //圆形裁剪框大小
    NSInteger left = 15;
    NSInteger widthHeight = SCREEN_WIDTH - 30;
    NSInteger top = (SCREEN_HEIGHT - widthHeight) / 2;
    self.imagePicker.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    @weakify(self);
    [self.imagePicker openAlbumCallBack:^(NSArray<UIImage *> *photos, NSArray *assets) {
        @strongify(self);
        if (photos.count > 0) {
            self.selectHeaderImg = photos[0];
            [self.tableview reloadData];
            //上传图片
            [self uploadPhotoRequestWithPhotosArr:@[self.selectHeaderImg]];
        }
    }];
}


//上传图片
- (void)uploadPhotoRequestWithPhotosArr:(NSArray *)photosArr {
    
    NSMutableArray *photoArr = [[NSMutableArray alloc] initWithArray:photosArr];
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    @weakify(self);
    
    [self showProgressView];
    [[[PigMarketApi sharedInstance] uploadPhotosWithPhotosArr:photoArr account:account type:UpDateImageType_Header] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        [self hideProgressView];
        Photos *photoModel = photoList.imgList[0];
        self.userInfoModel.headImg = photoModel.imgName;
        [self toastWithContent:@"头像上传成功"];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self hideProgressView];
        [self handlingError:error];
    }];
}


//刷新页面修改数据
- (void)refreshData {
    [self initData];
    [self.tableview reloadData];
}


//跳转VC
- (void)pushToModifyUserInfoVCWithTitle:(NSString *)title modifyUserInfoType:(ModifyUserInfoType)modifyUserInfoType {
    ModifyUserInfoViewController *modifyUserInfoViewController = [[ModifyUserInfoViewController alloc] init];
    modifyUserInfoViewController.title = title;
    modifyUserInfoViewController.modifyUserInfoType = modifyUserInfoType;
    modifyUserInfoViewController.userInfoModel = self.userInfoModel;
    [self.navigationController pushViewController:modifyUserInfoViewController animated:YES];
}



#pragma mark - photo delegate methods

- (void)pickerArea:(STPickerArea *)pickerArea province:(NSString *)province city:(NSString *)city area:(NSString *)area {
    self.area = [NSString stringWithFormat:@"%@%@%@",province,city,area];
    self.userInfoModel.regionName = self.area;
    [self refreshData];
}


- (void)pickerDate:(STPickerDate *)pickerDate year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    self.birthDate = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)year,(long)month,(long)day];
    self.userInfoModel.birthDate = self.birthDate;
    [self refreshData];
}

#pragma mark - delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataArr.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == self.aimsSection) {
        return self.photos.count >0 ?2 :1;
    }
    return [self.dataArr[section] count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 94;
    }
    if (indexPath.section == self.aimsSection && indexPath.row == 1) {
        return 77;
    }
    return 54;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (section == self.dataArr.count - 1 && self.aimTags.count >0) {
        
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
        footer.backgroundColor = KWhiteColor;
        [footer addSubview:self.tagsView];
        footer.height = self.tagsView.height;
        return footer;
    } else {
        return nil;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if ([self.title isEqualToString:PrefectPersonalInfoTitle] && section == self.dataArr.count - 1) {
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 32)];
        headView.backgroundColor = mBackgroudColor;
        UILabel *headTitle = [[UILabel alloc] init];
        headTitle.text = @"绑定第三方";
        headTitle.textColor = [UIColor colorWithHexString:@"#7C858A"];
        headTitle.font = [UIFont smallFont];
        [headView addSubview:headTitle];
        [headTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20);
            make.centerY.mas_equalTo(headView.mas_centerY);
        }];
        return headView;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.dataArr.count - 1 && self.dataArr.count>0) {
        return self.tagsView.height + 15;
    } else {
        return 0;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.title isEqualToString:@"完善个人资料"] && section == self.dataArr.count - 1) {
        return 32;
    }else {
        return 10;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == self.aimsSection && indexPath.row == 1) {
        
        MeatMePhotosCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMePhotosCell"];
        cell.images = self.photos;
        return cell;
    }
    
    UserInfoCell *cell = [UserInfoCell cellWithTableView:tableView];
    
    if (self.dataArr.count > indexPath.section) {
        if ([self.dataArr[indexPath.section] count] > indexPath.row) {
            NSDictionary *infoDic = self.dataArr[indexPath.section][indexPath.row];
            [cell configWithType:self.title infoDic:infoDic];
            
            //相册或拍照选择照片后  显示图片
            if (self.selectHeaderImg) {
                cell.detailIamgeView.image = self.selectHeaderImg;
            }
            return cell;
        }
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSDictionary *infoDic = self.dataArr[indexPath.section][indexPath.row];
    NSString *title = infoDic[@"title"];
    
    if ([title isEqualToString:@"头像"]) {
        
        NSArray *pictureArr = @[@"拍照",@"相册"];
        [self showAlertActionWithItemsArr:pictureArr];
        
    }else if ([title isEqualToString:@"昵称"]) {
        
        NSString *navTitle = [NSString stringWithFormat:@"修改%@",title];
        [self pushToModifyUserInfoVCWithTitle:navTitle modifyUserInfoType:ModifyUserInfoTypeName];
        
    }else if ([title isEqualToString:@"性别*"]) {
        
        NSArray *sexArr = @[@"男",@"女"];
        [self showAlertActionWithItemsArr:sexArr];
        
    }else if ([title isEqualToString:@"出生年月*"]) {
        
        [self showDatePicker];
    }else if ([title isEqualToString:@"所属城市*"]) {
        
        [self showAreaPicker];
        
    }else if ([title isEqualToString:@"设置密码*"]) {
        
        [self pushToModifyUserInfoVCWithTitle:title modifyUserInfoType:ModifyUserInfoTypePassword];
        
    }else if ([title isEqualToString:@"个性签名"]) {
        
        [self pushToModifyUserInfoVCWithTitle:title modifyUserInfoType:ModifyUserInfoTypePersonalRemark];
        
    }else if ([title isEqualToString:@"常用照片"]) {
        
        ModifyPhotoViewController *modifyPhotoViewController = [[ModifyPhotoViewController alloc] init];
        modifyPhotoViewController.dataArr = self.photos;
        [self.navigationController pushViewController:modifyPhotoViewController animated:YES];
        
    }else if ([title isEqualToString:@"微信"] || [title isEqualToString:@"支付宝"] || [title isEqualToString:@"QQ"] || [title isEqualToString:@"微博"]) {
        
        NSDictionary *dic = self.dataArr[indexPath.section][indexPath.row];
        self.bindOrUnbind = dic[@"detail"];
        NSString *message = [NSString stringWithFormat:@"是否%@",self.bindOrUnbind];
        
        @weakify(self);
        [[AlertAction sharedInstance] showAlertWithTitle:@"提示" message:message confirmBtnTitle:self.bindOrUnbind confirmBlock:^{
            @strongify(self);
            switch (indexPath.row) {
                case 0:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_WechatSession;
                }
                    break;
                case 1:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_QQ;
                    
                }
                    break;
                case 2:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_Sina;
                    
                }
                    break;
                default:
                    break;
            }
            //解绑 绑定sdk
            [self changeBindPlatform];
        }  cancelBlock:nil];
        
       // [self pushToModifyUserInfoVCWithTitle:title modifyUserInfoType:ModifyUserInfoTypePersonalRemark];
        
    }else if ([title isEqualToString:@"我的店铺"]) {
        
    }else if ([title isEqualToString:@"我的邀请人"]) {
        
        SelectInviterViewController *vc = [[SelectInviterViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if ([title isEqualToString:@"我的标签"]) {
        
        SelectTagsViewController *tagVC = [[SelectTagsViewController alloc] init];
        @weakify(self);
        [tagVC setSelectedTagsBlock:^(NSMutableDictionary<NSNumber *,NSString *> * _Nonnull selectedTagDic) {
            @strongify(self);
            [self tagsWithTagsDic:selectedTagDic];
            
            //更新tags显示
            NSArray *arr = selectedTagDic.allValues;
            self.tagsView.tagsArray = arr;
            self.tagsView.height = [self getFMTagViewHeight:self.tagsView];
            [self.tableview reloadData];
            
        }];
        tagVC.aimsTags = self.tagArray;
        [self.navigationController pushViewController:tagVC animated:YES];
        
    }
    
    if ([title hasSuffix:@"*"]) {//处理*变色
        title = [title substringToIndex:title.length - 1];
    }
}



#pragma mark - getter and setter

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.rowHeight = 54;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorColor = mIconLineColor;
        [_tableview registerClass:[MeatMePhotosCell class] forCellReuseIdentifier:@"MeatMePhotosCell"];
        
        UIView *footer = [[UIView alloc] init];
        footer.frame = CGRectMake(0, 0, KScreenWidth, 138);
        [footer addSubview:self.commitBtn];
        _tableview.tableFooterView = footer;
    }
    return _tableview;
}


- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}


- (UIButton *)commitBtn {
    if (!_commitBtn) {
        _commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_commitBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_commitBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_default"] forState:UIControlStateNormal];
        _commitBtn.frame = CGRectMake(30, 50, KScreenWidth - 60, 48);
    }
    return _commitBtn;
}


- (NSMutableArray *)photoNameArr {
    if (!_photoNameArr) {
        _photoNameArr = [[NSMutableArray alloc] init];
    }
    return _photoNameArr;
}


- (NSMutableArray<NSString *> *)selectTagsNameArr {
    if (!_selectTagsNameArr) {
        _selectTagsNameArr = [[NSMutableArray alloc] init];
    }
    return _selectTagsNameArr;
}


- (NSMutableArray<NSNumber *> *)selectTagsIdArr{
    if (!_selectTagsIdArr) {
        _selectTagsIdArr = [[NSMutableArray alloc] init];
    }
    return _selectTagsIdArr;
}


- (ImagePicker *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[ImagePicker alloc] init];
    }
    return _imagePicker;
}


- (FMTagsView *)tagsView
{
    if (!_tagsView) {
        _tagsView = [self setupFMTagsView];
    }
    return _tagsView;
}

- (NSMutableArray <Photos *>*)photos{
    
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
